package com.restaurantonlineorder.seller.aspect;

import com.restaurantonlineorder.exception.PermissionDeniedException;
import com.restaurantonlineorder.seller.service.IUserService;
import com.restaurantonlineorder.seller.vo.req.GoodsReqVo;
import lombok.SneakyThrows;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author 熊宇
 * @date 2022/7/25 10:22
 * @description 认证切面
 */
@Aspect
@Component
public class AuthorizeAspect {

    @Resource
    private IUserService iUserService;

    @SneakyThrows
    @Around("execution(* com.restaurantonlineorder.seller.service.impl.GoodsServiceImpl.save(..))")
    public Object checkPermission(ProceedingJoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        GoodsReqVo goodsReqVo = (GoodsReqVo) args[0];

        HttpServletRequest request = (HttpServletRequest) args[1];
        String phone = request.getHeader("phone");
        Long storeId = goodsReqVo.getStoreId();
        boolean isExist = iUserService.existsUserStoreByPhone(phone, storeId);

        if (!isExist) {
            throw new PermissionDeniedException("没有权限");
        }
        return joinPoint.proceed();
    }
}
